package com.cirkana.viewer.route;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.cirkana.CirkanaActivity;
import com.cirkana.CirkanaUtil;
import com.cirkana.serial.SerializationException;
import com.cirkana.viewer.R;
import com.cirkana.viewer.route.gpx.Tracker;
import com.cirkana.viewer.route.gpx.WayPoint;

public class RouteDetailActivity extends CirkanaActivity {

	public static final int RESULT_ROUTEDETAIL_OK = 0;

	private EditText titleEditText;
	private EditText descriptionEditText;
	private ImageView previewImageView;
	private EditText waypointsEditText;
	private Button selectButton;

	private RouteDetailPassData passData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.routedetail);

		this.titleEditText = (EditText) findViewById(R.id.routedetail_title);
		this.descriptionEditText = (EditText) findViewById(R.id.routedetail_description);
		this.previewImageView = (ImageView) findViewById(R.id.routedetail_route_preview);
		this.waypointsEditText = (EditText) findViewById(R.id.routedetail_waypoints);

		this.selectButton = (Button) findViewById(R.id.routedetail_select);

		this.passData = (RouteDetailPassData) getResult();

		setTrackerInfo(this.passData.getTracker());

		this.selectButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				try {
					setResult(RESULT_ROUTEDETAIL_OK, passData);
				} catch (SerializationException e) {
					openMessageBox("Error", e.getMessage());
				}
				finish();
			}
		});

	}

	private void setTrackerInfo(Tracker tracker) {

		this.titleEditText.setText(tracker.getMetadata().getName());
		this.descriptionEditText.setText(tracker.getMetadata().getDesc());
		tracker.getMetadata().getAuthor();
		try {
			this.previewImageView.setImageBitmap(CirkanaUtil.getImageBitmap(tracker.getMetadata().getPreview()));
		} catch (Exception e) {
			showErrorMessage(e);
		}

		StringBuilder s = new StringBuilder();
		for (WayPoint wayPoint : tracker.getWayPoints()) {
			s.append(wayPoint.getName() + "\n");
		}
		s.deleteCharAt(s.length() - 1);
		this.waypointsEditText.setText(s.toString());
	}

	public static Intent createIntent(Context context, Tracker tracker)
			throws SerializationException {
		Intent intent = new Intent(context, RouteDetailActivity.class);
		RouteDetailPassData data = new RouteDetailPassData();
		data.setTracker(tracker);
		setPassData(intent, data);
		return intent;
	}

}
